#!/bin/bash

DIR=`dirname $0`
CODE_DIR=`pwd`
APP=`basename $CODE_DIR`

SHA=$(head -n 1 .git/refs/heads/master)

if [[ ! -d /opt/solum/apps/$SHA ]]; then
  echo no app found for your current ref
  exit
fi

[[ -f ./openrc ]] && . ./openrc
[[ -f ~/devstack/openrc ]] && . ~/devstack/openrc

nova list 2> /dev/null > /dev/null
if [ $? != 0 ]; then
  echo 'cannot talk to nova. check your OpenStack credentials'
  exit 1
fi

nova secgroup-create $APP "allow ssh/web to $APP instance"
nova secgroup-add-rule $APP tcp 22 22 0.0.0.0/0
nova secgroup-add-rule $APP tcp 5000 5000 0.0.0.0/0


if [[ `nova keypair-list | grep ${APP} | wc -l` == 0 ]]; then
  nova keypair-add ${APP}_key > /opt/solum/apps/$SHA/key.priv
  chmod 0600 /opt/solum/apps/$SHA/key.priv
fi

nova boot --flavor=2 --image=cedarish --security-groups=$APP \
  --key-name=$APP_key --user-data=/opt/solum/apps/$SHA/user-data.txt \
  ${APP}01
